package com.demo.mystudy.ui.socketclient.clientcmd

import android.text.TextUtils
import com.demo.mystudy.event.DownloadFileEvent
import com.demo.mystudy.socketbean.DownloadFileBean
import com.demo.mystudy.socketbean.MessageWrapper
import com.demo.mystudy.ui.socketclient.WebSocketClientManager
import com.jetinno.simple.SimpleApplication.Companion.sContext
import com.jetinno.simple.utils.JsonUtil
import okio.ByteString
import org.greenrobot.eventbus.EventBus
import timber.log.Timber
import java.io.File
import java.io.FileOutputStream
import java.io.IOException

/**
 * Created by zhangyuncai on 2025/4/28.
 * 描述：
 */
object ClientCmdDownloadFile : ClientCmdInterface {
    private var currentFile: File? = null
    private var currentFileStream: FileOutputStream? = null
    private var currentFileSize: Long = 0
    private var receivedBytes: Long = 0
    override val cmd: String
        get() = "DownloadFile"

    /**
     * 请求下载文件
     */
    fun send(filePath: String) {
        val bean = DownloadFileBean()
        bean.cmd = cmd
        bean.filePath = filePath
        WebSocketClientManager.sendMessage(JsonUtil.anyToJson(bean))
    }

    /**
     * 接收Jetinno文件夹列表
     */
    override fun receive(messageWrapper: MessageWrapper) {
        val bean = JsonUtil.jsonToAny<DownloadFileBean>(
            messageWrapper.message,
            DownloadFileBean::class.java
        ) ?: return
        if (TextUtils.equals(bean.childCmd, "fileInfo")) {
            currentFile = File(sContext.filesDir, bean.filePath)
            val parentFile = currentFile!!.parentFile
            if (!parentFile!!.exists()) {
                parentFile!!.mkdirs()
                Timber.i("创建文件夹: $currentFile")
            } else {
                Timber.i("文件夹已存在: $currentFile")
            }
            currentFileSize = bean.fileInfoFileSize
            currentFileStream = FileOutputStream(currentFile)
            receivedBytes = 0
        } else if (TextUtils.equals(bean.childCmd, "fileEnd")) {
            currentFileStream?.close()
            currentFileStream = null
            Timber.i("文件接收完成: $bean.filePath")
            currentFile = null
            EventBus.getDefault().post(DownloadFileEvent())
        }
    }

    override fun receiveBinary(bytes: ByteString) {
        Timber.i("接收文件数据:")
        currentFileStream?.let { fos ->
            try {
                Timber.i("写入文件数据:")
                fos.write(bytes.toByteArray())
                receivedBytes += bytes.size.toLong()

                // 计算并显示进度（如果有文件大小信息）
                if (currentFileSize > 0) {
                    val progress = ((receivedBytes * 100) / currentFileSize).toInt()
                    Timber.i("文件接收进度: $progress%")
//                    runOnUiThread { progressBar.progress = progress }
                }
            } catch (e: IOException) {
                currentFileStream?.close()
                currentFileStream = null
            }
        }
    }

}